package com.easyattendance.servlets;

import java.io.IOException;
import java.io.PrintWriter;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Properties;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.easyattendance.model.Class;
import com.easyattendance.model.Parent;
import com.easyattendance.model.Section;
import com.easyattendance.model.Student;
import com.easyattendance.nls.UseProperties;
import com.easyattendance.services.AddClassService;
import com.easyattendance.services.AddParentService;
import com.easyattendance.services.AddSectionService;
import com.easyattendance.services.AddStudentService;
import com.easyattendance.services.ValidationsService;

@WebServlet(name = "AddStudentServlet", urlPatterns = { "/AddStudentServlet" })
public class AddStudentServlet extends HttpServlet {

	private static final long serialVersionUID = -1431408014242711487L;

	protected void processRequest(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/html;charset=UTF-8");
		PrintWriter out = response.getWriter();
		
		String actionType = request.getParameter("action_type");
		AddStudentService addStudentService = new AddStudentService();
		AddParentService addParentService = new AddParentService();
		ValidationsService validationsService = new ValidationsService();
		boolean dispatcherFlag = false;
		
		if(actionType.equals("create")) {
			/* Student Details */
			String studentFName = request.getParameter("student_fname");
			String studentLName = request.getParameter("student_lname");
			int student_roll_no = -1;
			if(!request.getParameter("student_roll_no").isEmpty()){
				student_roll_no=Integer.parseInt(request.getParameter("student_roll_no"));
			}
			String studentEmail = request.getParameter("student_email");
			String studentAddress = request.getParameter("student_address");			
			Long studentResiNo = 0L;
			if(!request.getParameter("student_resi_no").isEmpty()){
				 studentResiNo = Long.parseLong(request.getParameter("student_resi_no"));
			}
			Long studentMobile = 0L;
			if(!request.getParameter("student_mobile").isEmpty()){
				studentMobile = Long.parseLong(request.getParameter("student_mobile"));
			}			
			String studentGender = request.getParameter("gender_select");
			String studentDOB = request.getParameter("student_dob");
			
			String studentClassId = request.getParameter("student_classid");
			//String studentSectionId = request.getParameter("student_sectionid");
			String studentSectionEmail = request.getParameter("student_sectionid");

			
			/* Getting Parent Details */
			String parentName = request.getParameter("parent_name");
			String parentEmail = request.getParameter("parent_email");
			String parentJob = "";
			if(!request.getParameter("parent_job").isEmpty()){
				parentJob = request.getParameter("parent_job");
			}
			Long parentMobile = -1L;
			if(!request.getParameter("parent_mobile").isEmpty()){
				parentMobile = Long.parseLong(request.getParameter("parent_mobile"));
			} 
			Long parentOfficeNo = 0L;
			if(!request.getParameter("parent_office_no").isEmpty()){
				parentOfficeNo = Long.parseLong(request.getParameter("parent_office_no"));
			}			
			String parentGender = request.getParameter("parent_gender_select");
			
			if(studentFName.isEmpty()||studentLName.isEmpty()||student_roll_no < 0 || studentEmail.isEmpty() || studentAddress.isEmpty() || studentResiNo < 0 || parentName.isEmpty() || parentEmail.isEmpty() || parentGender.isEmpty() || parentMobile < 0){
				request.setAttribute("null_values", "All * fields are required");
				dispatcherFlag = true;
			}else{
				String validateFName = validationsService.validateName(studentFName);
				String validateLName = validationsService.validateName(studentLName);
				String validatePName = validationsService.validateName(parentName);
		        String validateEmail = validationsService.validateEmailId(studentEmail);
		        String validateParentEmail = validationsService.validateEmailId(parentEmail);
		        
		        if(validateFName.equals("Correct") && validateLName.equals("Correct") && validatePName.equals("Correct")) {
		        	dispatcherFlag = false;
		        	if(validateEmail.equals("Correct") && validateParentEmail.equals("Correct")) {
		        		dispatcherFlag = false;
		        	}else{
		        		request.setAttribute("email_not_valid", "Email(s) you entered is/are not valid.");
		        		dispatcherFlag = true;
		        	}
		        }else{
		        	request.setAttribute("name_not_valid", "Name(s) you entered is/are not valid.");
	        		dispatcherFlag = true;
		        }
			}
			

			if(!dispatcherFlag){
				
				SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
				java.util.Date studentBirthDate = null;
				try {
						studentBirthDate = format.parse(studentDOB);
				} catch (ParseException e) {
					e.printStackTrace();
				}
				
				Parent newParent = new Parent(parentName, parentEmail);
				boolean ifParentExists = addParentService.ifAlreadyExists(newParent);
				String parent_id = null;

				boolean result_student = false;
				boolean result = false;
				String studId=null;
				
				if (!ifParentExists) {
					
					Properties label_parent = UseProperties.loadProperties("Attendance.properties");
					//label_parent = UseProperties.incrementParentIdCounterValue(label_parent);
					parent_id = UseProperties.getParentIdPrefix(label_parent)+ addParentService.getParentIdValue();
	
					Student newStudent = new Student(studentFName, studentLName, studentEmail, studentAddress);
					boolean res = addStudentService.ifAlreadyExists(newStudent);
					
	
					if (studentSectionEmail != null) {
						AddSectionService sectionService = new AddSectionService();
						Section section = sectionService.getSectionBySectionEmail(studentSectionEmail);
						if (studentClassId != null) {
							AddClassService classService = new AddClassService();
							Class classes = classService.getClassById(studentClassId);
							if (!res) {
								Properties label_student = UseProperties.loadProperties("Attendance.properties");
								//label_student = UseProperties.incrementStudentIdCounterValue(label_student);
								studId = addStudentService.getStudentIdValue()+""; 
								
								newParent = new Parent(parent_id, parentName, parentEmail, parentMobile, studentResiNo, parentJob, parentOfficeNo, parentGender);
								Student student = new Student(studId, student_roll_no, studentFName, studentLName, studentEmail, studentAddress, studentResiNo, studentMobile, studentGender, studentBirthDate, section.getSection_id(), studentClassId);
								
								result= addParentService.addParentAndStudent(newParent,student);
								
							} else {
								request.setAttribute("studentAlreadyExist", "Student already exists.");
					        	RequestDispatcher rd = request.getRequestDispatcher("views/teacher/addStudent.jsp");
					        	rd.forward(request, response);
							}
						} else {
							request.setAttribute("classNotExist", "Class does not exist.");
				        	RequestDispatcher rd = request.getRequestDispatcher("views/teacher/addStudent.jsp");
				        	rd.forward(request, response);
						}
					} else {
						request.setAttribute("sectionNotExist", "Section does not exist.");
			        	RequestDispatcher rd = request.getRequestDispatcher("views/teacher/addStudent.jsp");
			        	rd.forward(request, response);
					}
				}
				else
				{
					Student newStudent = new Student(studentFName, studentLName,studentEmail, studentAddress);
					boolean res = addStudentService.ifAlreadyExists(newStudent);
					
					if (studentSectionEmail != null) {
						AddSectionService sectionService = new AddSectionService();
						Section section = sectionService.getSectionBySectionEmail(studentSectionEmail);
						if (studentClassId != null) {
							AddClassService classService = new AddClassService();
							Class classes = classService.getClassById(studentClassId);
							if (!res) {
								Properties label_student = UseProperties.loadProperties("Attendance.properties");
								label_student = UseProperties.incrementStudentIdCounterValue(label_student);
								studId = addStudentService.getStudentIdValue()+"";
	
								/*newParent = new Parent(parent_id, parentName, parentEmail,
										parentMobile, studentResiNo, parentJob,
										parentOfficeNo); */
	
								newParent=addParentService.getParentByEmailId(parentEmail);
								
								Student student = new Student(studId, student_roll_no,studentFName, studentLName, studentEmail,	studentAddress, studentResiNo, studentMobile,studentGender, studentBirthDate,section.getSection_id(), studentClassId);
								student.setParent(newParent);
								
								result_student = addStudentService.addStudent(student);
								//result_student= addParentService.addParentAndStudent(newParent,student);
	
							} else {
								request.setAttribute("studentAlreadyExist", "Student all ready exists.");
					        	RequestDispatcher rd = request.getRequestDispatcher("views/teacher/addStudent.jsp");
					        	rd.forward(request, response);
							}
						} else {
							request.setAttribute("classNotExist", "Class does not exist.");
				        	RequestDispatcher rd = request.getRequestDispatcher("views/teacher/addStudent.jsp");
				        	rd.forward(request, response);
						}
					} else {
						request.setAttribute("sectionNotExist", "Section does not exist.");
			        	RequestDispatcher rd = request.getRequestDispatcher("views/teacher/addStudent.jsp");
			        	rd.forward(request, response);
					}
				}
				try {
					if (result || result_student) {
						request.setAttribute("studentAdded", "Student added successfully.");
			        	RequestDispatcher rd = request.getRequestDispatcher("views/teacher/addStudent.jsp");
			        	rd.forward(request, response);
					} else {
						
						Properties label_parent = UseProperties.loadProperties("Attendance.properties");
						label_parent = UseProperties.decrementParentIdCounterValue(label_parent);
						
						Properties label_student = UseProperties.loadProperties("Attendance.properties");
						UseProperties.decrementStudentIdCounterValue(label_student);
						
						request.setAttribute("studentNotAdded", "Student not added successfully.");
			        	RequestDispatcher rd = request.getRequestDispatcher("views/teacher/addStudent.jsp");
			        	rd.forward(request, response);
					}
				} finally {
					out.close();
				}
			}//if not dispatcherFlag
			else{
				RequestDispatcher rd = request.getRequestDispatcher("views/teacher/addStudent.jsp");
	        	rd.forward(request, response);
			}
		}//if action type = create
		else if(actionType.equals("update")){
			int i = Integer.parseInt(request.getParameter("i_value"));
			
			/* Student Details */
			String studentId = request.getParameter("stud_id"+i);
			String studentFName = request.getParameter("stud_fname"+i);
			String studentLName = request.getParameter("stud_lname"+i);
			int student_roll_no=Integer.parseInt(request.getParameter("stud_roll_no"+i));

			String studentEmail = request.getParameter("stud_email_id"+i);
			String studentAddress = request.getParameter("stud_address"+i);
			Long studentResiNo = Long.parseLong(request.getParameter("stud_home_no"+i));
			Long studentMobile = Long.parseLong(request.getParameter("stud_mobile_no"+i));
			
			String studentGender = request.getParameter("gender_select"+i);
			
			String studentDOB = request.getParameter("stud_dob"+i);
			
			
			SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
			java.util.Date studentBirthDate = null;
			if(studentDOB != null) {
				try {
					studentBirthDate = format.parse(studentDOB);
				} catch (ParseException e) {
					e.printStackTrace();
				}
			}
			
			
			/* Getting Parent Details */

			String parentEmail = request.getParameter("parent_email"+i);
			Long parentMobile = Long.parseLong(request.getParameter("parent_mobile_no"+i));
			Long parentOfficeNo = Long.parseLong(request.getParameter("parent_office_no"+i));
			
			String parentGender = request.getParameter("parent_gender_select"+i);
			
			Student student = addStudentService.getStudentByStudentId(studentId);
			student.setStud_fname(studentFName);
			student.setStud_lname(studentLName);
			student.setStud_email_id(studentEmail);
			student.setStud_address(studentAddress);
			student.setStud_mobile_no(studentMobile);
			student.setStud_home_no(studentResiNo);
			student.setStud_gender(studentGender);
			student.setStud_dob(studentBirthDate);
				
			if(student.getStud_roll_no() != student_roll_no) {
				boolean ifAlreadyExists = addStudentService.getUserByUserId(student_roll_no);
				if(ifAlreadyExists) {
					request.setAttribute("rollNoExists", "The entered roll no is already assigned to another student.");
		        	RequestDispatcher rd = request.getRequestDispatcher("views/teacher/studentSettings.jsp");
		        	rd.forward(request, response);
				}
				else {
					student.setStud_roll_no(student_roll_no);
				}
			}
			
			
			Parent parent = student.getParent();
			
			parent.setParent_email_id(parentEmail);
			parent.setParent_mobile_no(parentMobile);
			parent.setParent_office_no(parentOfficeNo);
			parent.setParent_home_no(studentResiNo);
			parent.setGender(parentGender);
			
			boolean res1 = addStudentService.updateStudent(student);
			boolean res2 = addParentService.updateParentAndStudent(parent, student);
			
			if(res1) {
				if(res2) {
					request.setAttribute("studentParentUpdated", "Details updated.");
		        	RequestDispatcher rd = request.getRequestDispatcher("views/teacher/studentSettings.jsp");
		        	rd.forward(request, response);
				}
				else {
					request.setAttribute("studentParentNotUpdated", "Details not updated.");
		        	RequestDispatcher rd = request.getRequestDispatcher("views/teacher/studentSettings.jsp");
		        	rd.forward(request, response);
				}
			}
			else {
				request.setAttribute("studentParentNotUpdated", "Details not updated.");
	        	RequestDispatcher rd = request.getRequestDispatcher("views/teacher/studentSettings.jsp");
	        	rd.forward(request, response);
			}
		}
		else if(actionType.equals("delete")){
			int i = Integer.parseInt(request.getParameter("i_value"));
			String studentId = request.getParameter("stud_id"+i);
			
			boolean res = addStudentService.deleteStudent(studentId);
			
			if(res) {
				request.setAttribute("studentDeleted", "Student deleted successfully.");
	        	RequestDispatcher rd = request.getRequestDispatcher("views/teacher/studentSettings.jsp");
	        	rd.forward(request, response);
			}
			else {
				request.setAttribute("studentNotDeleted", "Student not deleted successfully.");
	        	RequestDispatcher rd = request.getRequestDispatcher("views/teacher/studentSettings.jsp");
	        	rd.forward(request, response);
			}
		}
		else {
			request.setAttribute("invalidChoice", "Invalid choice. Choose again.");
        	RequestDispatcher rd = request.getRequestDispatcher("views/teacher/studentSettings.jsp");
        	rd.forward(request, response);
		}

		
	}

	@Override
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		processRequest(request, response);
	}

	@Override
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		processRequest(request, response);
	}

	@Override
	public String getServletInfo() {
		return "Short description";
	}// </editor-fold>
}
